package com.wxtl.action;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.wxtl.action.base.BaseAction;
import com.wxtl.action.qo.LoginUser;
import com.wxtl.action.vo.Json;
import com.wxtl.entity.Agent;
import com.wxtl.entity.User;
import com.wxtl.service.AgentService;
import com.wxtl.service.UserService;
import com.wxtl.util.Constants;
import com.wxtl.util.Status;

public class LoginAction extends BaseAction {
	private LoginUser loginUser=new LoginUser();

	private UserService userService;
	private AgentService agentService;
	
	public AgentService getAgentService() {
		return agentService;
	}

	public void setAgentService(AgentService agentService) {
		this.agentService = agentService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public LoginUser getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(LoginUser loginUser) {
		this.loginUser = loginUser;
	}

	public UserService getUserService() {
		return userService;
	}

	public String login(){
		if(loginUser.getLoginType()==Status.AGENT_ACCOUNT){
			Agent agent = agentService.getAgentByNameAndPwd(loginUser);
			if(agent==null){
				super.getJson().setSuccess(false);
				super.getJson().setMsg("用户名或密码错误");
				return SUCCESS;
			}
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.setAttribute(Constants.ADMIN_SESSION_KEY, agent);
			session.setAttribute(Constants.ADMIN_SESSION_TYPE, loginUser.getLoginType());
			return SUCCESS;
		}else if(loginUser.getLoginType()==Status.SYS_ACCOUNT){
			//写入ip 和 date
			loginUser.setLoginDate(new Date());
			loginUser.setLoginIp(ServletActionContext.getRequest().getRemoteAddr());
			User u=userService.updateUserLoginInfo(loginUser);
			if(u==null){
				super.getJson().setSuccess(false);
				super.getJson().setMsg("用户名或密码错误");
				return SUCCESS;
			}
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.setAttribute(Constants.ADMIN_SESSION_KEY, u);
			session.setAttribute(Constants.ADMIN_SESSION_TYPE, loginUser.getLoginType());
			return SUCCESS;
		}else{
			super.getJson().setSuccess(false);
			super.getJson().setMsg("用户名或密码错误");
			return SUCCESS;
		}
	}
	
	public String logout(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.removeAttribute(Constants.ADMIN_SESSION_KEY);//移除
		session.invalidate();//session失效
		return SUCCESS;
	}
}
